package com.ykdl.member.kid.fragments;

import oauth.signpost.http.HttpParameters;
import net.wxxr.dataparse.model.DataParseError;
import net.wxxr.dataparse.model.DataState;
import net.wxxr.http.interfaces.ITag;
import net.wxxr.http.request.HttpBaseRequest;

import com.lidroid.xutils.BitmapUtils;
import com.sitech.oncon.barcode.core.BarCodeTestActivity;
import com.sitech.oncon.barcode.core.CaptureActivity;
import com.sitech.oncon.barcode.core.CreateBarCodeActivity;
import com.ykdl.member.KidApp;
import com.ykdl.member.base.QLog;
import com.ykdl.member.constant.KidAction;
import com.ykdl.member.constant.KidConfig;
import com.ykdl.member.kid.R;
import com.ykdl.member.kid.adapters.HotTopicAdapter;
import com.ykdl.member.kid.beans.HomeMessageCount;
import com.ykdl.member.kid.beans.Hot_TopicsBean;
import com.ykdl.member.kid.beans.IndexBean;
import com.ykdl.member.kid.chat.ChatActivity;
import com.ykdl.member.kid.chat.CommunicateAcivity;
import com.ykdl.member.kid.circle.TopicAndResultActivity;
import com.ykdl.member.kid.doctor.AskDoctorActivity;
import com.ykdl.member.kid.gears.ArticlesActivity;
import com.ykdl.member.kid.gears.ArticlesActivity_Demo;
import com.ykdl.member.kid.gears.BindStoreActivity;
import com.ykdl.member.kid.gears.HomeActivity;
import com.ykdl.member.kid.marketcard.CardScoreWapActivity;
import com.ykdl.member.kid.marketcard.CouponinfoWebView;
import com.ykdl.member.kid.marketcard.MyCouponActivity;
import com.ykdl.member.kid.marketcard.NewStoreCoupon;
import com.ykdl.member.kid.marketcard.StoreCouponActivity;
import com.ykdl.member.kid.prefs.MyPrefs;
import com.ykdl.member.kid.regandlogin.StateSelectActivity;
import com.ykdl.member.kid.regandlogin.YZLoginActivity;
import com.ykdl.member.kid.util.AccessTokenKeeper;
import com.ykdl.member.kid.util.MobileUtils;
import com.ykdl.member.kid.util.RequestAsAccessTokenUtil;
import com.ykdl.member.kid.util.VersionUdgrateUtil;
import com.ykdl.member.kid.widget.MyAdGallery;
import com.ykdl.member.kid.widget.RefreshListView;
import com.ykdl.member.kid.widget.MyAdGallery.MyOnItemClickListener;
import com.ykdl.member.kid.widget.RefreshListView.OnRefreshListener;
import com.ykdl.member.views.HScrollView;
import com.ykdl.member.views.HomeImageCarousel;
import com.ykdl.member.views.IaskMenuBarView;
import com.ykdl.net.manager.TaskManager;
import com.ykdl.net.manager.Wxxr;

import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout.LayoutParams;

public class HomeFragment extends BaseFragment_home implements OnRefreshListener {
	private HomeImageCarousel rl_home_image_carousel;
	public IndexBean homeBean = new IndexBean();
	private FragmentManager fragmentManager;
	private FragmentTransaction transaction;
	private HttpBaseRequest request;
	private IaskMenuBarView menu_bar;
	private HomeMessageCount messageCountBean;
	private VersionUdgrateUtil versionUdgrateUtil;
	private HScrollView sv_home;
	private boolean isExit = false;
	private MyAdGallery adgallery;
	private LinearLayout ovalLayout;
	private View view1;
	private RefreshListView pull_refresh_listview;
	private HotTopicAdapter adapter;
	private BitmapUtils bitmapUtil;
	private String RY_ID = "KEFU1423721923803";
	private static AccessTokenKeeper mTokenKeeper;
	private ImageView product_bt;
	private TextView product_info;
	@Override
	public View initView(LayoutInflater inflater) {
		initDatas();
		view = inflater.inflate(R.layout.homeactivity_xml, null);
		init();
		return view;
	}

	private void initDatas() {
//		showProgress();
		initMessageCount();//初始化消息个数
		String url = KidConfig.HOME_INDEX;
		request = Wxxr.getInstance().getRequest(url, null);
		TaskManager.startHttpRequest(request, new getHomeActivityTag(),
				IndexBean.class);
	}
	@Override
	public void initData(Bundle savedInstanceState) {
	}


	private void initMessageCount() {
		AccessTokenKeeper keeper = new AccessTokenKeeper(getActivity());
		if(keeper.getmisAnonymous()) return;
		if(!isConnect())return;
		String url = KidConfig.UNREAD_NEWS_COUNT ;
		HttpParameters bodyParams = new HttpParameters();
		request = Wxxr.getInstance().postBaseRequest(url, bodyParams,null
				);
		TaskManager.startHttpRequest(request, new getMessageCountTag(),
				HomeMessageCount.class);
	}

	private void init() {
		mTokenKeeper = new AccessTokenKeeper(mContext);
		bitmapUtil = new BitmapUtils(getActivity());
		bitmapUtil.configDefaultLoadingImage(R.drawable.unlonding_icon);
		bitmapUtil.configDefaultLoadFailedImage(R.drawable.unlonding_icon);
		pull_refresh_listview = (RefreshListView)view.findViewById(
				R.id.pull_refresh_list);
		pull_refresh_listview.setonRefreshListener(this); 
		view1 = LayoutInflater.from(getActivity()).inflate(
				R.layout.home_list_head_view, null);
		pull_refresh_listview.addHeaderView(view1);
		pull_refresh_listview.setAdapter(null);
		adapter = new HotTopicAdapter(getActivity());
		int screen_width = MobileUtils.getScreenWidthIntPx();
		adgallery = (MyAdGallery) view1.findViewById(R.id.adgallery);
		adgallery.setLayoutParams(new LinearLayout.LayoutParams(
				LayoutParams.MATCH_PARENT, (int) (screen_width * 0.1 / 0.3)));
		ovalLayout = (LinearLayout) view1.findViewById(R.id.ovalLayout);
		product_bt=(ImageView) view.findViewById(R.id.product_bt);
		product_info = (TextView) view.findViewById(R.id.product_info);
		view.findViewById(R.id.top_right_lp_top).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						// 去我的优惠卷
					Intent intent = new Intent(mContext,MyCouponActivity.class); 
					intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						startActivity(intent);
					}
				});
		view.findViewById(R.id.ask_kefu).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						// 去客服   CommunicateAcivity
					Intent intent = new Intent(mContext,CommunicateAcivity.class); 
						startActivity(intent);
					}
				});
		view.findViewById(R.id.ask_doctor).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						// 去医生
						Intent intent = new Intent(mContext,AskDoctorActivity.class);
						startActivity(intent);
					}
				});
		view.findViewById(R.id.ask_yys).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						// 去营养师     ChatActivity
						Intent intent = new Intent(mContext, ChatActivity.class); //ChatActivity.class
						intent.putExtra(KidAction.COOPERATIVE_CORP_ID, "100000001");
						intent.putExtra(KidAction.SEVRVER_NAME, "营养师");
						startActivity(intent);
					}
				});
		view.findViewById(R.id.ask_yrh).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(mContext,ArticlesActivity.class);
				startActivity(intent);
			}
		});
		view.findViewById(R.id.store_bt).setOnClickListener(
				new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						// 去门店
						if (null!=homeBean.getRandom_store()) {
							if (homeBean.getRandom_store().getStatus()!=2) {
								Toast.makeText(mContext, "该门店不能提供服务", 1).show();
								return;
							}
							Intent intent = new
									 Intent(mContext,NewStoreCoupon.class);
							intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
							intent.putExtra(KidAction.STORE_ID, homeBean.getRandom_store().getStore_id()+"");
							intent.putExtra(KidAction.STORE_NAME, homeBean.getRandom_store().getName()+"");
									 startActivity(intent);
						}
						 
					}
				});
		view.findViewById(R.id.product_bt).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						// 去商品
						if (null!=homeBean.getRandom_product()) {
							Intent intent = new Intent(mContext, CouponinfoWebView.class);
							intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
							intent.putExtra(KidAction.PRODUCT_ID, homeBean.getRandom_product().getProduct_id());
							intent.putExtra(KidAction.URL_TYPE, 1);
							intent.putExtra(KidAction.STORE_ID, homeBean.getRandom_product().getStore_id());
									 startActivity(intent);
						}
						 
					}
				});
		view.findViewById(R.id.lottery_prize_bt).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						// 玩转积分
						if (null!=homeBean.getRandom_lottery_prize()) {
						Intent intent = new Intent(mContext, CouponinfoWebView.class);
						intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						intent.putExtra(KidAction.RANDOM_LOTTERY_PRIZE, homeBean.getRandom_lottery_prize());
						intent.putExtra(KidAction.URL_TYPE, 4);
						 startActivity(intent);
					}
						}
				});
		view.findViewById(R.id.exchange_gift_bt).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						// 积分换礼
						if (null!=homeBean.getRandom_exchange_gift()) {
							Intent intent = new Intent(mContext, CardScoreWapActivity.class);
							intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
							intent.putExtra(KidAction.POINT_TYPE_ID, homeBean.getRandom_exchange_gift().getPoint_type_id());
							intent.putExtra(KidAction.URL_TYPE, 0);
									 startActivity(intent);
						}
					}
				});
		view.findViewById(R.id.right_bt).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub         BarCodeTestActivity
				Intent intent = new Intent(mContext, CaptureActivity.class);
				startActivity(intent);
			}
		});
		
	pull_refresh_listview.setOnItemClickListener(new OnItemClickListener() {
		
		 @Override
		 public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
		 long arg3) {
		 // TODO Auto-generated method stub
		 Hot_TopicsBean bean = (Hot_TopicsBean) adapter.getItem(arg2 - 1);
		 Intent intent = new Intent(mContext,TopicAndResultActivity.class);
		 intent.putExtra(TopicAndResultActivity.STR_TOPIC_ID,bean.getTopic_id() + "");
		 intent.putExtra(TopicAndResultActivity.STR_GROUP_ID, bean.getGroup_id() + "");
		 startActivity(intent);
		 }
		 });

	}

	class getHomeActivityTag implements ITag {
		@Override
		public void refreshUI(Object t, DataState ds) {
			pull_refresh_listview.onRefreshComplete();
			if (t instanceof IndexBean) {
				finishProgress();
				homeBean = (IndexBean) t;
				if (null!=homeBean.getRandom_product()) {
					product_info.setText(homeBean.getRandom_product().getName());
					if (null!=homeBean.getRandom_product().getList_pic()) {
						bitmapUtil.display(product_bt, homeBean.getRandom_product().getList_pic().getFile_url());
					}
					
					
				}
				if (homeBean.getHot_topics().size()>0) {
					adapter.setList(homeBean.getHot_topics());
					pull_refresh_listview.setAdapter(adapter);	
				}
				if (homeBean.getTop_ad_items().size()>0) {
					show_home_image_carousel();
				
					
					}else {
						
//						delayedDismissdialog();
//						showErrorTip("", "没有数据");
					}
				if (homeBean.getInvitation_stores()!=null) {
					if(homeBean.getInvitation_stores().getStore_list()!=null ){
						Intent intent=new Intent(mContext, BindStoreActivity.class);
						intent.putExtra("Invitation_store", homeBean.getInvitation_stores());
						startActivityForResult(intent, 100);
				    }
				}
				
					pull_refresh_listview.onRefreshComplete();
					pull_refresh_listview.setFecthMoreOk();
					pull_refresh_listview.setMoreButtoIsGon(true);
			}
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			// DataParseCode errorCode = parseError.getErrorCode();
//			String errmsg = parseError.getErrMsg();
			finishProgress();
			pull_refresh_listview.onRefreshComplete();
			pull_refresh_listview.setFecthMoreOk();
//			Toast.makeText(mContext, errmsg, 0).show();
			return true;
		}

		@Override
		public void refreshCancel() {
		}
	}

	/**
	 * 展示图片轮播数据
	 */
	public void show_home_image_carousel() {

		if (homeBean.getTop_ad_items().size() > 0) {
			adgallery.start(getActivity(), 5000, ovalLayout,
					R.drawable.dot_focused, R.drawable.dot_normal,
					homeBean.getTop_ad_items());
			adgallery.setMyOnItemClickListener(new MyOnItemClickListener() {
				@Override
				public void onItemClick(int curIndex) {
					 goAction(homeBean.getTop_ad_items().get(curIndex).getAction());
				}
			});
		}

	}
	
	public static boolean isConnect() {
		// 获取手机所有连接管理对象（包括对wi-fi,net等连接的管理）
		try {
			ConnectivityManager connectivity = (ConnectivityManager)KidApp.getInstance().getApplicationContext()
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			if (connectivity != null) {
				// 获取网络连接管理的对象
				NetworkInfo info = connectivity.getActiveNetworkInfo();
				if (info != null && info.isConnected()) {
					// 判断当前网络是否已经连接
					// if (info.getState() == NetworkInfo.State.CONNECTED) {
					return true;
					// }
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			QLog.debug("error", e.toString());
		}
		return false;
	}
	
	class getMessageCountTag implements ITag{
		@Override
		public void refreshUI(Object t, DataState ds) {
			if(null != t && t instanceof HomeMessageCount){
				messageCountBean = (HomeMessageCount)t;
				if(messageCountBean.isExpired()){
					RequestAsAccessTokenUtil.getInstance(mContext).refreshTokenRequest(request, this, HomeMessageCount.class);
				}else{
					settingMessageCount();
				}
				
			}
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			return true;
		}

		@Override
		public void refreshCancel() {
		}
	}
	public void settingMessageCount() {
		if (messageCountBean.getUnread_count() > 0) {
//			menu_bar.setMessageBar(true);
			MyPrefs.setMessageCount(getActivity(), "1");
		}else {
//			menu_bar.setMessageNoBar();
			MyPrefs.setMessageCount(getActivity(), null);
		}
	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		initDatas();
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if(resultCode==200){
			((HomeActivity)getActivity()).setAtItem();
		}
	}
}
